#调试屏幕，快捷键F9
#剧情树导出函数
default debug_data = {}

init python:
    import json, os
    def refresh_storyline():
        store.debug_data = generate_storyline()
        renpy.notify("剧情树已刷新 ✅")

    def export_storyline():
        data = generate_storyline()
        filepath = os.path.join(renpy.config.basedir, "storyline.json")
        with open(filepath, "w", encoding="utf-8") as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        renpy.notify("✅ 剧情树已导出到 storyline.json")

screen debug_screen():
    modal False
    zorder 100

    frame:
        align (0.02, 0.05)
        xsize 700  # 增加宽度以显示更多内容
        ysize 600
        background "#0008"
        padding (10,10)
        vbox:
            label "📖 剧情树调试工具"

            viewport:
                draggable True
                mousewheel True
                scrollbars "vertical"
                ysize 450

                vbox:
                    for lbl, info in debug_data.get("labels", {}).items():
                        # 点击 label 可以直接 jump
                        textbutton "[lbl]" action Jump(lbl) text_size 20 text_color "#66ccff"

                        if info["jumps"]:
                            text "  Jumps → " + ", ".join(info["jumps"]) size 16 color "#ffcc66"
                        else:
                            text "  Jumps → (无)" size 16 color "#888888"

                        if info["menus"]:
                            for menu_index, menu in enumerate(info["menus"]):
                                text "  Menu {}:".format(menu_index + 1) size 16 color "#99ff99"
                                for option in menu["options"]:
                                    text "    \"{}\" → jump {}".format(option["text"], option["jump"]) size 14 color "#ccccff"
                        else:
                            text "  Menus → (无)" size 16 color "#888888"

                        text ""  # 空行分隔

            hbox:
                textbutton "刷新剧情树" action Function(refresh_storyline)
                textbutton "导出剧情树" action Function(export_storyline)
                textbutton "可视化剧情树" action Show("story_tree_screen")
                textbutton "关闭" action Hide("debug_screen")

init python:
    import renpy.exports as renpy_exports

    def toggle_debug_screen():
        if renpy_exports.get_screen("debug_screen"):  
            renpy_exports.hide_screen("debug_screen")   # 如果已打开 → 关闭
        else:
            renpy_exports.show_screen("debug_screen")   # 如果没打开 → 打开

    # 绑定 F9 作为切换键
    config.underlay.append(renpy.Keymap(
        K_F9=toggle_debug_screen
    ))